<template>
  <div>
    <div class="flex flex-col items-center justify-center h-full">
      <DatePicker
        class="v-date-picker"
        color="red"
        :is-dark="isDark()"
        is-range
        v-model="vCalendarData.selectedDate"
        @update:model-value="handleChange"
      />
      <div class="w-full max-w-400px text-18px bg-background flex flex-col items-center justify-end rounded-md shadow-md mt-2 py-4 my-3">
        <h1 class="mb-auto mt-0 leading-none">Todos</h1>
        <ul class="w-full list-none px-3.5 overflow-x-hidden mt-8">
          <li @click="updateTask(index,{id:task.id,status:task.status=='doing'?'done':'doing'})" 
              v-for="(task, index) in taskList" 
              :key="index" 
              class="flex items-center leading-normal relative px-3 py-0 transition-transform duration-500 ease-in-out"
              :class="{'todo--completed':task.status=='done'}">
            <span class="todo__content">{{ task.title }}</span>
            <i @click.stop="showDesc=index" class="fa fa-list-ul ml-2.5"></i>
            <i @click.stop="addTask=task,showEdit=index" class="fa fa-pencil-square-o ml-2.5" aria-hidden="true"></i>
          </li>
        </ul>
        <div class="w-3/4 relative my-4">
          <input class="add-todo__input" v-model="addTask.title" placeholder="添加一个任务标题...">
          <button class="add-todo__btn" @click="saveTask()"><i class="fa fa-plus"></i></button>
        </div>
      </div>
      
      <!-- 编辑弹窗 -->
      <div v-if="showEdit!=-1" @click="showEdit=-1" class="fixed inset-0 bg-black bg-opacity-30 z-1">
        <div @click.stop="showEdit" class="todos-edit">
          <h1 class="todo-title">Todos Edit</h1>
          <div class="todos-input-line" v-for="(value, key) in addTask" :key="key">
            <label class="todos-edit-label" :for="key">{{ key }}:</label>
            <el-date-picker
              v-if="typeof value === 'string' && value.match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="addTask[key]"
            ></el-date-picker>
            <el-input
              v-else-if="typeof value === 'string' || typeof value === 'number'" 
              :type="typeof value === 'number' ? 'number' : 'textarea'" :id="key" 
              v-model="addTask[key]"
              placeholder="请输入一些文本"
            ></el-input>
            <el-input-number v-else-if="typeof value === 'number'" :id="key" v-model="addTask[key]"></el-input-number>
            <el-input v-else type="text" v-model="addTask[key]" placeholder="请输入一些文本"></el-input>
          </div>
          <button class="todos-edit-save-btn" @click.stop="updateTask(showEdit,addTask),showEdit=-1">保存</button>
        </div>
      </div>
      
      <!-- 详情弹窗 -->
      <div v-if="showDesc!=-1" @click="showDesc=-1" class="fixed inset-0 bg-black bg-opacity-30 z-1">
        <div @click.stop="showEdit" class="todos-desc">
          <h1 class="todo-title">{{taskList[showDesc].title}}</h1>
          <div class="todos-desc-line">{{taskList[showDesc].status}}</div>
          <div class="todos-desc-line">从{{taskList[showDesc].startTime}} <br/> 到{{taskList[showDesc].endTime}}</div>
          <div class="todos-desc-line">执行者：{{taskList[showDesc].executor}}</div>
          <div class="todos-desc-main" v-html="taskList[showDesc].description"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue';
import { DatePicker } from 'v-calendar';
import 'v-calendar/style.css'; // 导入v-calendar样式
import { useMainStore } from '../../store';
  
export default {
  components: {
    DatePicker
  },

  setup() {
    const { proxy } = getCurrentInstance();
    const store = useMainStore();
    const card = ref(null);
    const vCalendarData = reactive({
      selectedDate: {
        start: new Date(new Date().getTime() - 2 * 24 * 60 * 60 * 1000),
        end: new Date(new Date().getTime() + 2 * 24 * 60 * 60 * 1000)
      }
    });
    const wallpaperIndex = ref(0);
    const showEdit = ref(-1);
    const showDesc = ref(-1);
    const wallpapers = ref([]);
    const collects = ref({});
    const taskList = ref([]);
    const addTask = reactive({
      "title": "每日提交代码",
      "dependencyId": 0,
      "description": "这里是简介",
      "status": "doing",
      "startTime": formatDateToString(new Date()),
      "endTime": formatDateToString(new Date()),
      "urgency": 1,
      "executor": "0",
    });

    // 在组件创建时调用
    const handleChange = (newDate) => {
      const startDate = new Date(newDate.start);
      startDate.setHours(0, 0, 0, 0); // 将时间部分设置为 0
      const endDate = new Date(newDate.end);
      endDate.setHours(23, 59, 59, 999); // 将时间部分设置为 0
      getTasks({startTime: formatDateToString(startDate), endTime: formatDateToString(endDate)});
    };

    // 组件创建后执行
    onMounted(() => {
      const current = new Date();
      vCalendarData.selectedDate.start = new Date(current);
      vCalendarData.selectedDate.start.setDate(current.getDate() - 2);
      vCalendarData.selectedDate.end = new Date(current);
      vCalendarData.selectedDate.end.setDate(current.getDate() + 2);
      handleChange(vCalendarData.selectedDate);
    });

    function isDark() {
      return document.documentElement.getAttribute('theme') == 'dark';
    }

    function saveTask(task) {
      task = task ?? addTask;
      proxy.$http.post(proxy.$constant.baseURL + "/todolist/saveTask", task, true)
        .then((res) => {
          if (res.code == 200) {
            taskList.value.push(task);
            addTask.title = "";
          }
        })
        .catch((error) => {
          proxy.$message({
            message: error.message,
            type: "error"
          });
        });
    }

    function updateTask(index, task) {
      proxy.$http.post(proxy.$constant.baseURL + "/todolist/updateTask", task, true)
        .then((res) => {
          if (res.code == 200) {
            taskList.value[index].status = res.data.status;
          }
        })
        .catch((error) => {
          proxy.$message({
            message: error.message,
            type: "error"
          });
        });
    }

    function getTasks(selectedDate) {
      proxy.$http.post(proxy.$constant.baseURL + "/todolist/listTask", selectedDate)
        .then((res) => {
          if (!proxy.$common.isEmpty(res)) {
            taskList.value = res.data;
          }
        })
        .catch((error) => {
          proxy.$message({
            message: error.message,
            type: "error"
          });
        });
    }

    function formatDateToString(fdate) {
      let date = new Date(fdate); // 获取当前时间
      let year = date.getFullYear().toString().padStart(4, '0'); // 年份
      let month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份
      let day = date.getDate().toString().padStart(2, '0'); // 日期
      let hour = date.getHours().toString().padStart(2, '0'); // 小时
      let minute = date.getMinutes().toString().padStart(2, '0'); // 分钟
      let second = date.getSeconds().toString().padStart(2, '0'); // 秒钟
      let datetimeString = `${year}-${month}-${day} ${hour}:${minute}:${second}`; // 生成日期时间字符串
      return datetimeString;
    }

    return {
      card,
      vCalendarData,
      wallpaperIndex,
      showEdit,
      showDesc,
      wallpapers,
      collects,
      taskList,
      addTask,
      isDark,
      saveTask,
      updateTask,
      getTasks,
      handleChange,
      formatDateToString
    };
  }
}
</script>

<style scoped>
.todo__content {
  position: relative;
  opacity: 1;
  text-transform: capitalize;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: opacity 0.25s ease-out;
}

.todo__content:after {
  content: '';
  position: absolute;
  display: block;
  width: calc( 100% + .5em);
  left: -.25em;
  height: 2px;
  top: 50%;
  border-radius: 1px;
  background: var(--fontColor);
  transform-origin: center right;
  transform: scaleX(0);
  transition: transform 0.5s cubic-bezier(0.55, 0, 0.1, 1);
}

.todo--completed:after {
  font-family: FontAwesome;
  content: "\f00c";
  position: absolute;
  right: .75rem;
  color: #2ecc71;
  opacity: 1;
  transform: scale(1);
}

.todo--completed .todo__content {
  opacity: 0.5;
}

.todo--completed .todo__content:after {
  transform: scaleX(1);
  transform-origin: center left;
}

.add-todo__input {
  width: 100%;
  border-radius: 5px;
  padding: .5rem 1rem;
  background: #e8ebed;
  margin: 0;
  outline: 0;
  border: 2px solid #e8ebed;
  transition: background .25s ease-out;
}

.add-todo__input:focus {
  background: none;
}

.add-todo__btn {
  text-align: center;
  color: #fafafa;
  line-height: 1;
  position: absolute;
  font-size: 120%;
  right: 0;
  top: 50%;
  border-radius: 50%;
  width: 48px;
  height: 48px;
  background: #2ecc71;
  opacity: 0;
  transform: translate(0, -50%) scale(0) rotate(180deg);
  transition: transform, opacity, 0.5s cubic-bezier(0.87, -0.41, 0.19, 1.44);
}

.add-todo__input:focus + .add-todo__btn {
  opacity: 1;
  transform: translate(50%, -50%) scale(1) rotate(0deg);
}

.add-todo__btn:focus {
  opacity: 1;
  transform: translate(50%, -50%) scale(1.1) rotate(0deg);
}

.add-todo__btn:active {
  opacity: 1;
  transition: transform, opacity, 0.1s cubic-bezier(0.87, -0.41, 0.19, 1.44);
  transform: translate(50%, -50%) scale(0.95) rotate(0deg);
}

.cursor {
  margin-left: 1px;
  animation: hideToShow 0.7s infinite;
  font-weight: 200;
}

@keyframes hideToShow {
  0%, 100% { opacity: 0; }
  50% { opacity: 1; }
}

/* 保留原有弹窗样式 */
.todos-desc {
  width: 90vw;
  max-width: 400px;
  height: 480px;
  background-color: var(--background);
  padding: 20px;
  display: flex;
  flex-direction: column;
  box-shadow: #3e3e3e 1px 5px 20px;
  border-radius: 8px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  transition: .3s;
}

.todos-desc-line {
  padding: 2px 0px 0px 10px; 
}

.todos-desc-main {
  overflow-y: scroll;
  flex: 1;
}

.todos-edit {
  width: 90vw;
  max-width: 400px;
  height: 480px;
  overflow-y: scroll;
  background-color: var(--background);
  padding: 20px;
  box-shadow: #3e3e3e 1px 5px 20px;
  border-radius: 8px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  transition: .3s;
  z-index: 115;
}

.todos-input-line {
  margin: 5px;
}

.todos-edit-label {
  color: var(--fontColor);
  vertical-align: middle;
  width: 100px;
  height: 36px;
  line-height: 36px;
  overflow: hidden;
  padding-right: 5px;
  white-space: nowrap;
  text-overflow: ellipsis;
  display: inline-block;
}

.todos-edit-save-btn {
  background: var(--themeBackground);
  width: 100%;
  height: 40px;
  color: #FFF;
  text-align: center;
  outline: none;
  border: none;
}

.todo-title {
  margin-bottom: auto;
  margin-top: 0;
  line-height: 1;
}

@media screen and (max-width: 620px) {
  .v-date-picker {
    width: 90vw;
  }
}
</style>